<template>
	<!-- <a-card>
		<a-checkbox-group v-model="checkedList" :options="options" @change="handleCheckboxChange" />
		<a-table
			ref="tableRef"
			:columns="columns"
			:data-source="dataList"
			:scroll="{ x: '200%', y: tableHeight }"
			:pagination="false"
			bordered
			:customRow="customRowHandler"
		>
			<template #bodyCell="{ column, record, text, index }">
				<template
					v-if="
						column.dataIndex === 'commissionAchievementRate' ||
						column.dataIndex === 'monRepayAr' ||
						column.dataIndex === 'lastMonRepayAr' ||
						column.dataIndex === 'momDiff'
					"
				>
					<a-progress
						:percent="text"
						:stroke-color="getProgressColor(text)"
						:status="text >= 100 ? 'success' : 'normal'"
						stroke-linecap="round"
						text-position="inside"
					/>
				</template>
				<template v-if="column.dataIndex === 'monthlyAchievementAmount'">
					<a-space>
						<a @click="userTableRef.onOpen(record)">{{ text }}</a>
						<a-divider type="vertical" />
					</a-space>
				</template>
				<template v-if="column.dataIndex === 'advancePayment' && record.deptName !== '小计' && text !== '0'">
					<a-space>
						<a @click="advanceRef.onOpen(record)">{{ text }}</a>
						<a-divider type="vertical" />
					</a-space>
				</template>
			</template>
			<template #summary>
				<a-table-summary fixed>
					<a-table-summary-row>
						<a-table-summary-cell
							style="text-align: center; position: sticky; left: 0; background-color: #fff; z-index: 1"
						>
							总计
						</a-table-summary-cell>
						<a-table-summary-cell
							style="text-align: center; position: sticky; left: 100px; background-color: #fff; z-index: 1"
						/>
						<a-table-summary-cell />
						<a-table-summary-cell style="text-align: center">{{ summary.personnelCount }} </a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">{{ summary.caseCount }}</a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">{{ summary.totalArrearsAmount }} </a-table-summary-cell>
						<a-table-summary-cell style="text-align: center; color: #ff0000"
							>{{ summary.monthlyTargetAmount }}
						</a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">
							<a-space>
								<a @click="userTableRef.onOpen(record)">{{ summary.monthlyClientAmount }}</a>
								<a-divider type="vertical" />
							</a-space>
						</a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">
							<a-space>
								<a @click="userTableRef.onOpen(record)">{{ summary.monthlySubsidiaryAmount }}</a>
								<a-divider type="vertical" />
							</a-space>
						</a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">
							<a-space>
								<a @click="userTableRef.onOpen(record)">{{ summary.monthlyVarianceAmount }}</a>
								<a-divider type="vertical" />
							</a-space>
						</a-table-summary-cell>
						<a-table-summary-cell style="text-align: center"></a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">{{ summary.commission }} </a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">{{ summary.advancePayment }} </a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">{{ summary.commissionExclAdv }} </a-table-summary-cell>
						<a-table-summary-cell style="text-align: center">{{ summary.commissionTarget }} </a-table-summary-cell>
						<a-table-summary-cell style="text-align: center" />
						<a-table-summary-cell style="text-align: center" />
						<a-table-summary-cell style="text-align: center"
							>{{ summary.lastMonthlyTargetAmount }}
						</a-table-summary-cell>
						<a-table-summary-cell style="text-align: center"
							>{{ summary.lastMonthlyAchievementAmount }}
						</a-table-summary-cell>
						<a-table-summary-cell style="text-align: center"
							>{{ summary.lastMonthlyAdvancePayment }}
						</a-table-summary-cell>
						<a-table-summary-cell style="text-align: center" />
						<a-table-summary-cell style="text-align: center" />
					</a-table-summary-row>
				</a-table-summary>
			</template>
		</a-table>
	</a-card> -->
	<div>
		<a-space class="mb-3 mt-3">
			<a-checkbox
				v-model:checked="checkState.checkAll"
				:indeterminate="checkState.indeterminate"
				@change="onCheckAllChange"
			>
				所有模块
			</a-checkbox>
			<a-divider type="vertical" style="background-color: #fff" />
			<a-checkbox-group v-model:value="checkState.checkedList" :options="checkOptions" @change="onCheckListChange" />
		</a-space>
		<a-table
			ref="tableRef"
			:columns="filerAfterColumns"
			:data-source="dataList2"
			:scroll="{ y: tableHeight }"
			:pagination="false"
			bordered
			:expandRowByClick="true"
			:indentSize="20"
			rowKey="id"
			:defaultExpandedRowKeys="defaultExpandedKeys"
			:rowClassName="getrowClassName"
			:loading="loading"
		>
			<template #bodyCell="{ column, record, text, index }">
				<template v-if="column.dataIndex === 'perEntrustCnt'">
					<a-tooltip>
						<template #title>调解员总数：{{ record.staffCnt }}</template>
						{{ record.perEntrustCnt }}
					</a-tooltip>
				</template>
				<template v-if="column.dataIndex === 'lastPerEntrustCnt'">
					<a-tooltip>
						<template #title>调解员总数：{{ record.lastStaffCnt }}</template>
						{{ record.lastPerEntrustCnt }}
					</a-tooltip>
				</template>
				<template
					v-if="
						column.dataIndex === 'totalRepay' &&
						record.batch !== '项目小计' &&
						record.projectName !== '产品小计' &&
						record.productName !== '合计' &&
						text !== '0'
					"
				>
					<a-space>
						<a @click="userTableRef.onOpen(record)">{{ text }}</a>
					</a-space>
				</template>
				<template
					v-if="
						column.dataIndex === 'totalAdvance' &&
						record.batch !== '项目小计' &&
						record.projectName !== '产品小计' &&
						record.productName !== '合计' &&
						text !== '0'
					"
				>
					<a-space>
						<a @click="advanceRef.onOpen(record)">{{ text }}</a>
					</a-space>
				</template>
			</template>
			<template #summary>
				<a-table-summary fixed>
					<a-table-summary-row>
						<!-- 固定列 -->
						<a-table-summary-cell
							style="text-align: center; position: sticky; left: 0; background-color: #fff; z-index: 1"
						>
							总计
						</a-table-summary-cell>
						<a-table-summary-cell />
						<a-table-summary-cell />
						<a-table-summary-cell />
						<!-- 委案模块 -->
						<a-table-summary-cell v-if="checkState.checkedList.includes('委案模块')" style="text-align: center"
							>{{ summary.entrustAmt }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('委案模块')" style="text-align: center">{{
							summary.perEntrustCnt
						}}</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('委案模块')" style="text-align: center">{{
							summary.lastEntrustAmt
						}}</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('委案模块')" style="text-align: center">
							{{ summary.lastPerEntrustCnt }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('委案模块')" style="text-align: center">
							{{ summary.entrustAmtMomDiff * 100 + '%' }}
						</a-table-summary-cell>
						<!-- 回款模块 -->
						<a-table-summary-cell
							v-if="checkState.checkedList.includes('回款模块')"
							style="text-align: center; color: #ff0000"
							>{{ summary.repayTarget }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('回款模块')" style="text-align: center">
							<!-- <a-space>
								<a @click="userTableRef.onOpen(record)">{{ summary.totalRepay }}</a>
							</a-space> -->
							{{ summary.totalRepay }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('回款模块')" style="text-align: center">
							<!-- <a-space>
								<a @click="userTableRef.onOpen(record)">{{ summary.branchRepay }}</a>
							</a-space> -->
							{{ summary.branchRepay }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('回款模块')" style="text-align: center">{{
							summary.repayDiff
						}}</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('回款模块')" style="text-align: center">{{
							summary.addRepay
						}}</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('回款模块')" style="text-align: center">{{
							summary.taskCompleteRate * 100 + '%'
						}}</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('回款模块')" style="text-align: center">{{
							summary.tcrMomDiff
						}}</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('回款模块')" style="text-align: center">
							{{ summary.repayMomDiff * 100 + '%' }}
						</a-table-summary-cell>
						<!-- 创佣模块 -->
						<a-table-summary-cell v-if="checkState.checkedList.includes('创佣模块')" style="text-align: center">
							{{ summary.commTarget }}</a-table-summary-cell
						>
						<a-table-summary-cell v-if="checkState.checkedList.includes('创佣模块')" style="text-align: center"
							>{{ summary.totalComm }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('创佣模块')" style="text-align: center"
							>{{ summary.totalAdvance }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('创佣模块')" style="text-align: center"
							>{{ summary.netComm }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('创佣模块')" style="text-align: center">{{
							summary.yesterdayNet
						}}</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('创佣模块')" style="text-align: center"
							>{{ summary.commCompleteRate }}
						</a-table-summary-cell>
						<a-table-summary-cell v-if="checkState.checkedList.includes('创佣模块')" style="text-align: center">{{
							summary.commMomDiff
						}}</a-table-summary-cell>
					</a-table-summary-row>
				</a-table-summary>
			</template>
		</a-table>
	</div>
	<RepaymentChart ref="userTableRef" />
	<AdvanceInfo ref="advanceRef" />
</template>

<script setup>
	import monthlyApi from '@/api/bi/goals/monthly/monthlyApi.js'
	import planApi from '@/api/bi/plan/planApi.js'
	import dayjs from 'dayjs'
	import RepaymentChart from '@/views/bi/progress/repaymentChart.vue'
	import AdvanceInfo from '@/views/bi/progress/advanceInfo.vue'
	import BigNumber from 'bignumber.js'
	import { notification } from 'ant-design-vue'
	//=============================================DATA========================================================================
	const tableHeight = ref()
	const advanceRef = ref()
	const tableRef = ref()
	const userTableRef = ref()
	const dataList = ref([])
	const dataList2 = ref([])
	const summary = ref({
	})
	// const columns = [
	// 	{
	// 		title: '所属部门',
	// 		dataIndex: 'deptName',
	// 		align: 'center',
	// 		fixed: 'left',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					display: record.deptRowSpan === 0 ? 'none' : undefined,
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				},
	// 				rowSpan: record.deptRowSpan
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '项目名称',
	// 		dataIndex: 'projectName',
	// 		align: 'center',
	// 		fixed: 'left',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				},
	// 				rowSpan: record.projectRowSpan
	// 			}
	// 		}
	// 	},

	// 	{
	// 		title: '批次',
	// 		dataIndex: 'batchNumber',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '人数',
	// 		dataIndex: 'personnelCount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '案件数量',
	// 		dataIndex: 'caseCount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		},
	// 		summary: true
	// 	},
	// 	{
	// 		title: '案件总金额',
	// 		dataIndex: 'totalArrearsAmount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '月目标金额',
	// 		dataIndex: 'monthlyTargetAmount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined,
	// 					color: '#FF0000'
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '当月甲方还款金额',
	// 		dataIndex: 'monthlyClientAmount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '当月分公司上报金额',
	// 		dataIndex: 'monthlySubsidiaryAmount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '当月还款差额',
	// 		dataIndex: 'monthlyVarianceAmount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '结佣比例',
	// 		dataIndex: 'commissionRatio',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '佣金',
	// 		dataIndex: 'commission',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '垫付金额',
	// 		dataIndex: 'advancePayment',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '去掉垫付的佣金',
	// 		dataIndex: 'commissionExclAdv',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '佣金目标',
	// 		dataIndex: 'commissionTarget',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '佣金达成率',
	// 		dataIndex: 'commissionAchievementRate',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '月还款达成率',
	// 		dataIndex: 'monRepayAr',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '月度目标（环比）',
	// 		dataIndex: 'lastMonthlyTargetAmount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '累计达成（环比）',
	// 		dataIndex: 'lastMonthlyAchievementAmount',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '垫付（环比）',
	// 		dataIndex: 'lastMonthlyAdvancePayment',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '完成率（环比）',
	// 		dataIndex: 'lastMonRepayAr',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	},
	// 	{
	// 		title: '环比差异',
	// 		dataIndex: 'momDiff',
	// 		align: 'center',
	// 		customCell: (record, index) => {
	// 			return {
	// 				style: {
	// 					background: record.isSubtotal ? '#f0f0f0' : undefined
	// 				}
	// 			}
	// 		}
	// 	}
	// ]
	const columns2 = [
		{
			title: '所属部门',
			dataIndex: 'deptName',
			// dataIndex: 'deptId',
			align: 'center',
			fixed: 'left',
			width: 180,
			ellipsis: true,
			customRender: ({ text, record }) => {
				if (record.productName !== '合计') {
					return ''
				}
			},
			customCell: (record, index) => {
				return {
					style: {
						background: record.isSubtotal ? '#1C233A' : undefined
					}
				}
			}
		},
		{
			title: '产品名称',
			dataIndex: 'productName',
			align: 'center',
			fixed: 'left',
			width: 100,
			ellipsis: true,
			customRender: ({ text, record }) => {
				if (record.projectName !== '产品小计' && record.productName !== '合计') {
					return ''
				}
			},
			customCell: (record, index) => {
				return {
					style: {
						background: record.isSubtotal ? '#1C233A' : undefined
					}
				}
			}
		},
		{
			title: '项目名称',
			dataIndex: 'projectName',
			align: 'center',
			fixed: 'left',
			width: 150,
			ellipsis: true,
			customRender: ({ text, record }) => {
				if (record.batch !== '项目小计' && record.projectName !== '产品小计') {
					return ''
				}
			},
			customCell: (record, index) => {
				return {
					style: {
						background: record.isSubtotal ? '#1C233A' : undefined
					}
				}
			}
		},
		{
			title: '批次',
			dataIndex: 'batch',
			align: 'center',
			fixed: 'left',
			width: 100,
			ellipsis: true
		},
		{
			title: '委案模块',
			children: [
				{
					title: '当月委案',
					children: [
						{
							title: '委案金额',
							dataIndex: 'entrustAmt',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '人均载案量',
							dataIndex: 'perEntrustCnt',
							align: 'center',
							width: 120,
							ellipsis: true
						}
					]
				},
				{
					title: '环比上月',
					children: [
						{
							title: '委案金额',
							dataIndex: 'lastEntrustAmt',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '人均载案量',
							dataIndex: 'lastPerEntrustCnt',
							align: 'center',
							width: 120,
							ellipsis: true
						},
						{
							title: '差异率',
							dataIndex: 'entrustAmtMomDiff',
							align: 'center',
							width: 150,
							ellipsis: true,
							customRender: ({ text, record }) => {
								return text === '--' ? '--' : `${(record.entrustAmtMomDiff * 100).toFixed(2)}%`
							}
						}
					]
				}
			]
		},
		{
			title: '回款模块',
			children: [
				{
					title: '当月回款',
					children: [
						{
							title: '回款任务',
							dataIndex: 'repayTarget',
							align: 'center',
							width: 150,
							ellipsis: true,
							customCell: (record, index) => {
								return {
									style: {
										color: '#FF0000'
									}
								}
							}
						},
						{
							title: '累计达成',
							dataIndex: 'totalRepay',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '分总上报回款',
							dataIndex: 'branchRepay',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						// {
						// 	title: '回款差值', //当月累计达成-当月分总上报回款
						// 	dataIndex: 'repayDiff',
						// 	align: 'center',
						// 	width: 150,
						// 	ellipsis: true
						// },
						{
							title: '新增回款',
							dataIndex: 'addRepay',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '回款差',//分总上报回款-累计回款
							dataIndex: 'repayDiff',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '任务完成率',
							dataIndex: 'taskCompleteRate',
							align: 'center',
							width: 150,
							ellipsis: true,
							customRender: ({ text, record }) => {
								return text === '--' ? '--' : `${(record.taskCompleteRate * 100).toFixed(2)}%`
							}
						}
					]
				},
				{
					title: '环比上月',
					children: [
						{
							title: '完成率差异',
							dataIndex: 'tcrMomDiff',
							align: 'center',
							width: 150,
							ellipsis: true,
							customRender: ({ text, record }) => {
								return text === '--' ? '--' : `${(record.tcrMomDiff * 100).toFixed(2)}%`
							}
						},
						{
							title: '累计达成绝对值差异',
							dataIndex: 'repayMomDiff',
							align: 'center',
							width: 180,
							ellipsis: true
						}
					]
				}
			]
		},
		{
			title: '创佣模块',
			width: 150,
			ellipsis: true,
			children: [
				{
					title: '当月创佣',
					children: [
						{
							title: '佣金目标',
							dataIndex: 'commTarget',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '创佣',
							dataIndex: 'totalComm',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: 'DF',
							dataIndex: 'totalAdvance',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '创佣（扣DF）',
							dataIndex: 'netComm',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '昨日创佣（扣DF）',
							dataIndex: 'yesterdayNet',
							align: 'center',
							width: 150,
							ellipsis: true
						},
						{
							title: '佣金目标达成率',
							dataIndex: 'commCompleteRate',
							align: 'center',
							width: 150,
							ellipsis: true,
							customRender: ({ text, record }) => {
								return text === '--' ? '--' : `${(record.commCompleteRate * 100).toFixed(2)}%`
							}
						}
					]
				},
				{
					title: '环比上月',
					children: [
						{
							title: '创佣绝对值差异（扣DF）',
							dataIndex: 'commMomDiff',
							align: 'center',
							width: 200,
							ellipsis: true
						}
					]
				}
			]
		}
	]
	let filerAfterColumns = ref([...columns2.slice(0, 4)])
	const defaultExpandedKeys = ref([]) //默认展开行
	// const checkedList = ref(columns.map((item) => item.key))
	// const options = columns.map(({ key, title }) => ({
	// 	label: title,
	// 	value: key
	// }))
	const formatter = new Intl.NumberFormat('zh-CN')
	const formatNumber = (num) => formatter.format(num.toNumber()) // 格式化数字
	// const formatPercentage = (num) => `${num}`
	// const formatPercentage2 = (num) => `${(num * 100).toFixed(2)}%`
	// let checkAll = ref(true)
	// let checkList = ref()
	let checkOptions = ref(['委案模块', '回款模块', '创佣模块'])
	const checkState = ref({
		indeterminate: false,
		checkAll: true,
		checkedList: ['委案模块', '回款模块', '创佣模块']
	})
	let loading = ref(false)
	//=============================================METHODS========================================================================
	const onCheckAllChange = (e) => {
		if (!e.target.checked) {
			notification.warning({
				message: '请至少勾选一个模块',
				placement: 'top'
			})
		}
		Object.assign(checkState.value, {
			checkedList: e.target.checked ? checkOptions.value : [],
			indeterminate: false
		})
		filterColumns()
	}
	const onCheckListChange = (list) => {
		if (list.length === 0) {
			notification.warning({
				message: '请至少勾选一个模块',
				placement: 'top'
			})
		}
		if (list.length === checkOptions.value.length) {
			Object.assign(checkState.value, {
				checkAll: true,
				indeterminate: false
			})
		} else {
			Object.assign(checkState.value, {
				checkAll: false,
				indeterminate: true
			})
		}
		filterColumns()
	}
	//根据勾选模块筛选展示列
	const filterColumns = () => {
		filerAfterColumns.value = [
			...columns2.slice(0, 4),
			...columns2.slice(4).filter((item) => checkState.value.checkedList.includes(item.title))
		]
		// console.log('filerAfterColumns', filerAfterColumns.value)
	}
	//千位分隔符数字转普通数字
	const thousandNum = (num) => {
		if (!num) {
			return '0'
		}
		return new BigNumber(num.replace(/,/g, '').replace(/%/g, ''))
	}

	const getList = () => {
		//旧日报
		// monthlyApi.list(dayjs().format('YYYYMM')).then((res) => {
		// 	// 集合转Map,计算小计，合计，总计
		// 	const dataMap = list2Map(res)
		// 	//map转集合
		// 	const list = map2List(dataMap)
		// 	//计算合并的行数
		// 	dataList.value = processData(list)
		// })
		loading.value = true
		// 新日报
		planApi.list(dayjs().format('YYYYMM')).then((res) => {
			//产品名称的替换
			res.forEach((item) => {
				if (item.productName === '好还') {
					item.productName = '微财科技'
				} else if (item.productName === '有钱花') {
					item.productName = '度小满'
				}
			})
			//集合转Map,计算小计，合计，总计
			const dataMap1 = list2Map1(res)
			//自定义计算一些内容
			// cusTomCalc1(dataMap1)
			//map转集合
			const list1 = map2List1(dataMap1)
			// //计算合并的行数
			dataList2.value = toExpand1(list1)
			//一些批次委案金额为1的，只展示回款相关数据
			const batchEquaOne = ['batch', 'totalRepay', 'branchRepay', 'addRepay', 'totalComm'] //展示相关字段
			console.log('b', dataList2.value)
			dataList2.value.forEach((item) => {
				item.children.forEach((child) => {
					child.children.forEach((subChild) => {
						subChild.children.forEach((hid) => {
							if (hid.entrustAmt == 1) {
								for (const key in hid) {
									if (!batchEquaOne.includes(key)) {
										hid[key] = '--'
									}
								}
							}
						})
					})
				})
			})
			loading.value = false
		})
	}

	const processData = (rawData) => {
		const result = {}
		rawData.forEach((item) => {
			const deptName = item.deptName
			const projectName = item.projectName
			if (!result[deptName]) {
				result[deptName] = {
					deptRowSpan: 0,
					projects: {}
				}
			}
			if (!result[deptName].projects[projectName]) {
				result[deptName].projects[projectName] = 0
			}
			result[deptName].projects[projectName] += 1
			result[deptName].deptRowSpan += 1
		})
		const deptCountMap = new Map()
		const projectCountMap = new Map()
		rawData.forEach((item) => {
			if (item.projectName && item.deptName) {
				//判断是否已经获取过数量，只给第一条赋值
				if (!deptCountMap.has(item.deptName)) {
					deptCountMap.set(item.deptName, result[item.deptName].deptRowSpan)
					item.deptRowSpan = result[item.deptName].deptRowSpan
				} else {
					item.deptRowSpan = 0
				}
				if (!projectCountMap.has(item.deptName + '@' + item.projectName)) {
					projectCountMap.set(item.deptName + '@' + item.projectName, result[item.deptName].projects[item.projectName])
					item.projectRowSpan = result[item.deptName].projects[item.projectName]
				} else {
					item.projectRowSpan = 0
				}
			}
		})
		return rawData
	}

	/**
	 *
	 * @param {*} data 原始数据
	 * @param {*} numFiled 统计数字类的字段
	 * @param {*} filed 非统计数字类的字段
	 * @returns 处理后的数据
	 * 注意：创佣需要计算出各项之后，再计算小计，总计，合计的汇总（佣金比例不汇总，算做非统计数字类字段）
	 */

	const list2Map1 = (data) => {
		let total = {} //总计
		let deptTotal = {} //合计
		let productTotal = {} //产品小计
		let projectTotal = {} //项目小计
		let numFiled = [] //统计数字类的字段
		let filed = [
			'batch',
			'belongingMonth',
			'deptId',
			'deptName',
			'id',
			'productCode',
			'productName',
			'projectCode',
			'projectName',
			'commRatio',
			'repaymentDetail'
		] //非统计数字类的字段

		//需要计算的汇总字段，比如人均载案量合计的时候，不能是子项的人均相加，而是子项的案件量总和/人力总和
		const needCalc = [
			'perEntrustCnt',
			'lastPerEntrustCnt',
			'entrustAmtMomDiff',
			'taskCompleteRate',
			'tcrMomDiff',
			'commCompleteRate'
		]

		for (let key in data[0]) {
			if (!filed.includes(key)) {
				total['total' + key] = new BigNumber(0)
				deptTotal['deptTotal' + key] = new BigNumber(0)
				productTotal['productTotal' + key] = new BigNumber(0)
				projectTotal['projectTotal' + key] = new BigNumber(0)
				numFiled.push(key)
			}
		}
		const result = new Map()
		data.forEach((item) => {
			const { deptName, deptId, productName, projectName, ...detail } = item
			// if (!result.has(deptName)) {
			// 	result.set(deptName, {
			// 		deptName,
			// 		productList: []
			// 	})
			// }
			// const dept = result.get(deptName)
			if (!result.has(deptId)) {
				result.set(deptId, {
					deptName,
					deptId,
					productList: []
				})
			}
			const dept = result.get(deptId)
			//检查产品是否已经存在
			let product = dept.productList.find((p) => p.productName === productName)
			//如果产品不存在，初始化产品
			if (!product) {
				product = {
					deptName,
					deptId,
					productName,
					projectList: []
				}
				dept.productList.push(product)
			}
			//检查项目是否已经存在
			let project = product.projectList.find((p) => p.projectName === projectName)
			//如果项目不存在，初始化项目
			if (!project) {
				project = {
					deptName,
					deptId,
					projectName,
					productName,
					detail: []
				}
				product.projectList.push(project)
			}
			//添加详细信息
			project.detail.push({ deptName, productName, projectName, ...detail })
		})
		result.forEach((dept) => {
			for (let key in deptTotal) {
				deptTotal[key] = new BigNumber(0)
			}
			dept.productList.forEach((product) => {
				for (let key in productTotal) {
					productTotal[key] = new BigNumber(0)
				}
				product.projectList.forEach((project) => {
					for (let key in projectTotal) {
						projectTotal[key] = new BigNumber(0)
					}
					project.detail.forEach((item) => {
						for (let i = 0; i < numFiled.length; i++) {
							item[numFiled[i]] = item[numFiled[i]] == null ? '0' : formatNumber(new BigNumber(item[numFiled[i]]))
							if (!needCalc.includes(numFiled[i])) {
								projectTotal['projectTotal' + numFiled[i]] = projectTotal['projectTotal' + numFiled[i]].plus(
									new BigNumber(item[numFiled[i]].replace(/,/g, ''))
								)
							}
							if (item.batch !== '项目小计' && !needCalc.includes(numFiled[i])) {
								//合计
								deptTotal['deptTotal' + numFiled[i]] = deptTotal['deptTotal' + numFiled[i]].plus(
									new BigNumber(item[numFiled[i]].replace(/,/g, ''))
								)
								// 产品小计
								productTotal['productTotal' + numFiled[i]] = productTotal['productTotal' + numFiled[i]].plus(
									new BigNumber(item[numFiled[i]].replace(/,/g, ''))
								)
								//总计
								total['total' + numFiled[i]] = total['total' + numFiled[i]].plus(
									new BigNumber(item[numFiled[i]].replace(/,/g, ''))
								)
							}
						}
					})
					//追加项目小计行
					const projectxiaoji = {}
					for (let i = 0; i < numFiled.length; i++) {
						projectxiaoji[numFiled[i]] = formatNumber(projectTotal['projectTotal' + numFiled[i]])
					}
					//需要计算的项目小计字段
					for (let i = 0; i < needCalc.length; i++) {
						projectxiaoji[needCalc[i]] = customCalc(projectxiaoji, needCalc[i])
					}
					project.detail.push({
						isSubtotal: true,
						batch: '项目小计',
						...projectxiaoji
					})
				})
				//追加产品小计行
				const productxiaoji = {}
				for (let i = 0; i < numFiled.length; i++) {
					productxiaoji[numFiled[i]] = formatNumber(productTotal['productTotal' + numFiled[i]])
				}
				//需要计算的产品小计字段
				for (let i = 0; i < needCalc.length; i++) {
					productxiaoji[needCalc[i]] = customCalc(productxiaoji, needCalc[i])
				}
				product.projectList.push({
					// isSubtotal: true,
					projectName: '产品小计',
					...productxiaoji
				})
			})
			//追加合计行
			const heji = {}
			for (let i = 0; i < numFiled.length; i++) {
				heji[numFiled[i]] = formatNumber(deptTotal['deptTotal' + numFiled[i]])
			}
			//需要计算的产品小计字段
			for (let i = 0; i < needCalc.length; i++) {
				heji[needCalc[i]] = customCalc(heji, needCalc[i])
			}
			dept.productList.push({
				productName: '合计',
				...heji
			})
		})
		//总计
		const zongji = {}
		for (let i = 0; i < numFiled.length; i++) {
			zongji[numFiled[i]] = formatNumber(total['total' + numFiled[i]])
		}
		summary.value = {
			...zongji
		}
		// console.log('rr', result)
		// console.log('list2map', Array.from(result.values()))
		return Array.from(result.values()) // 转换为数组
	}

	// const map2List = (data) => {
	// 	return data.reduce((acc, dept) => {
	// 		// 对每个部门中的项目列表进行处理
	// 		const flattenedProjects = dept.projectList.reduce((projectsAcc, project) => {
	// 			// 对每个项目中的详情列表进行处理
	// 			const flattenedDetails = project.detail.map((detail) => ({
	// 				deptName: dept.deptName,
	// 				projectName: project.projectName,
	// 				...detail // 拷贝详情对象的属性
	// 			}))
	// 			return projectsAcc.concat(flattenedDetails)
	// 		}, [])
	// 		return acc.concat(flattenedProjects)
	// 	}, [])
	// }

	const map2List1 = (data) => {
		return data.reduce((acc, dept) => {
			// 处理部门下的产品列表
			const flattenedProducts = dept.productList.reduce((productsAcc, product) => {
				// 处理产品下的项目列表
				if (product.projectList) {
					const flattenedProjects = product.projectList.reduce((projectsAcc, project) => {
						// 处理项目下的详情列表
						if (project.detail) {
							const flattenedDetails = project.detail.map((detail) => ({
								deptName: dept.deptName,
								deptId: dept.deptId,
								productName: product.productName || '', // 确保有产品名称
								projectName: project.projectName,
								...detail
							}))
							return projectsAcc.concat(flattenedDetails)
						} else {
							// 处理没有 detail 的项目（如产品小计）
							return projectsAcc.concat({
								deptName: dept.deptName,
								deptId: dept.deptId,
								productName: product.productName || '', // 确保有产品名称
								...project
							})
						}
					}, [])
					return productsAcc.concat(flattenedProjects)
				} else {
					// 处理没有 projectList 的产品（如合计）
					return productsAcc.concat({
						deptName: dept.deptName,
						deptId: dept.deptId,
						productName: product.productName || '', // 确保有产品名称
						...product,
						detail: product.detail || []
					})
				}
			}, [])
			return acc.concat(flattenedProducts)
		}, [])
	}
	// 自定义行处理器，用于处理行点击等事件
	const customRowHandler = (record, index) => ({
		onClick: (event) => {
			if (record.projectName !== '小计') {
				console.log('准备跳转路由...' + record.projectCode)
			}
		}
	})
	const calculateTableHeight = () => {
		const windowHeight = window.innerHeight
		const headerHeight = 200
		const footerHeight = 100
		tableHeight.value = windowHeight - headerHeight - footerHeight
	}
	// 监听窗口大小变化
	const handleResize = () => {
		calculateTableHeight()
	}
	const getProgressColor = (value) => {
		const values = Number(value)
		if (values <= 30) {
			return '#e60000'
		} else if ((values > 30) & (values <= 80)) {
			return '#1890fe'
		} else if (values > 80) {
			return '#49aa19'
		}
	}
	// 处理复选框变化
	const handleCheckboxChange = (value) => {
		checkedList.value = value
	}
	const toExpand1 = (data) => {
		let deptGroup = []
		data.forEach((item) => {
			if (item.productName === '合计') {
				deptGroup.push({
					...item,
					// id: `${item.deptName}`,
					id: `${item.deptId}`,
					children: []
				})
				//添加默认展开行
				defaultExpandedKeys.value.push(`${item.deptId}`)
			}
		})
		data.forEach((item) => {
			if (item.projectName === '产品小计') {
				const dept = deptGroup.find((d) => d.deptId === item.deptId)
				if (dept) {
					dept.children.push({
						...item,
						id: `${item.deptId}-${item.productName}`,
						children: []
					})
					// defaultExpandedKeys.value.push(`${item.deptId}-${item.productName}`)
				}
			}
		})
		data.forEach((item) => {
			if (item.batch === '项目小计') {
				const dept = deptGroup.find((d) => d.deptId === item.deptId)
				if (dept) {
					const product = dept.children.find((p) => p.productName === item.productName)
					product.children.push({
						...item,
						id: `${item.productName}-${item.projectName}`,
						children: []
					})
				}
			}
		})
		data.forEach((item) => {
			if (item.projectName !== '产品小计' && item.batch !== '项目小计' && item.productName !== '合计') {
				const dept = deptGroup.find((d) => d.deptId === item.deptId)
				if (dept) {
					const product = dept.children.find((p) => p.productName === item.productName)
					if (product) {
						const project = product.children.find((p) => p.projectName === item.projectName)
						if (project) {
							project.children.push(item)
						}
					}
				}
			}
		})
		return deptGroup
	}
	const getrowClassName = (record, index) => {
		if (record.batch === '项目小计') {
			return 'subtotal-row'
		}
		return ''
	}

	//=============================================LIFE HOOKS========================================================================
	const isZero = (num1, num2) => {
		if (num1 == 0 || num2 == 0) {
			return true
		}
		return false
	}

	const customCalc = (data, field) => {
		switch (field) {
			// 人均载案量 = 委案户数/人力
			case 'perEntrustCnt':
				return isZero(data.entrustCnt, data.staffCnt)
					? 0
					: (thousandNum(data.entrustCnt) / thousandNum(data.staffCnt)).toFixed(0)
			case 'lastPerEntrustCnt':
				return isZero(data.lastEntrustCnt, data.lastStaffCnt)
					? 0
					: (thousandNum(data.lastEntrustCnt) / thousandNum(data.lastStaffCnt)).toFixed(0)
			// 差异率 = （本月委案金额-上月委案金额）/上月委案金额
			case 'entrustAmtMomDiff':
				return isZero(data.entrustAmt, data.lastEntrustAmt)
					? `0`
					: (thousandNum(data.entrustAmt) - thousandNum(data.lastEntrustAmt)) / thousandNum(data.lastEntrustAmt)
			//当月任务完成率 = 累计达成/回款任务
			case 'taskCompleteRate':
				return isZero(data.totalRepay, data.repayTarget)
					? `0`
					: thousandNum(data.totalRepay) / thousandNum(data.repayTarget)
			//完成率差异 = 当月任务完成率-上月任务完成率
			case 'tcrMomDiff':
				const tcr = isZero(data.totalRepay, data.repayTarget)
					? `0`
					: thousandNum(data.totalRepay) / thousandNum(data.repayTarget)
				const lastTcr = isZero(data.lastTotalRepay, data.lastRepayTarget)
					? `0`
					: thousandNum(data.lastTotalRepay) / thousandNum(data.lastRepayTarget)
				return isZero(tcr, lastTcr) ? `0` : tcr - lastTcr
			//佣金完成率=净累计创佣/佣金目标
			case 'commCompleteRate':
				return isZero(data.netComm, data.commTarget) ? `0` : thousandNum(data.netComm) / thousandNum(data.commTarget)
			default:
				break
		}
	}
	onBeforeUnmount(() => {
		window.removeEventListener('resize', handleResize)
	})
	onMounted(() => {
		filterColumns()
		getList()
		calculateTableHeight()
		window.addEventListener('resize', handleResize)
	})
</script>
<style lang="less" scoped>
	//重写表格样式
	:deep(.ant-spin-container) {
		.ant-table-header {
			.ant-table-thead {
				th {
					background: #1e284a;
					color: #fff;
					// border-inline-end: 1px solid #1e4b9c!important;
				}
			}
		}
		.ant-table-body {
			background: #1a233c;
			color: #fff;
			td,
			.ant-table-row-expand-icon {
				background: #1a233c;
				color: #fff;
			}
			// td {
			// 	border-inline-end: 1px solid #1e4b9c!important;
			// }
			&::-webkit-scrollbar-thumb {
				background: #4b5d99;
				border-radius: 3px;
			}
			&::-webkit-scrollbar-track {
				background: #202848;
				border-radius: 3px;
			}
		}
		//hover行背景色
		.ant-table-tbody > tr.ant-table-row:hover > td,
		.ant-table-tbody > tr > td.ant-table-cell-row-hover {
			background: #20275b !important;
			color: #fff;
		}
		//空数据状态样式
		.ant-table-placeholder {
			.ant-empty-description {
				color: #fff !important;
			}
			.ant-table-cell:hover {
				background: #1a233c !important;
			}
		}
		// 添加小计行样式
		.subtotal-row {
			td {
				background: #2d365c;
				color: #fff;
			}
			&:hover > td {
				background: #2d365c;
			}
		}
		//总计行样式
		.ant-table-summary {
			.ant-table-cell {
				background: #2d365c !important;
				color: #fff;
			}
		}
	}
	//勾选框样式
	:deep(.ant-checkbox-group-item) {
		color: #fff;
	}
	:deep(.ant-checkbox-wrapper) {
		color: #fff;
	}
</style>
